const STORAGE_KEY='search-list'
//最大的缓存数量
const HISTORY_MAX =10
export default {
	//独立命名空间
	namespaced:true,
	//通过state声明数据
	state:()=>{
		return { 
			//搜索历史数据
			searchData:uni.getStorageSync(STORAGE_KEY)||[]
			}
	},
	mutations:{
		//保存数据到storage中
		searchToStorage(state){
			uni.setStorage({
				key:STORAGE_KEY,
				data:state.searchData
			})
		},
		//添加数据
		addSearchData(state,val){
			if(!val) return 
			const index = state.searchData.findIndex(item=>item===val)
			if(index !== -1){
				state.searchData.splice(index,1)
			}
			//把搜索结果添加到头部
			state.searchData.unshift(val)
			//添加数据大于10条删除
			if(state.searchData.length > HISTORY_MAX){
				state.searchData.splice(HISTORY_MAX,state.searchData.length - HISTORY_MAX)
			}
			//通过this.commit调用mutation,接收一个字符串为当前mutation路径this.commit（模块名/mutation名）
			this.commit('search/searchToStorage')
		},		
		//删除指定数据
		removeSearchData(state,index){
			state.searchData.splice(index,1)
			this.commit('search/searchToStorage')
		},
		//删除全部数据
		removeAllSearchData(state){
			state.searchData=[]
			this.commit('search/searchToStorage')
		}
	}
}